const { Op } = require("sequelize");

const artClassModel = appRequire('models/artClass');
const artPPTModel = appRequire('models/artPPT');

// 导出对象，供其它模块调用
module.exports = {
    list,
    save,
    destroy,
    changeOrder,
};

async function changeOrder(req, request) {
    let postData = req.body
    let returnData = Common.clone(Constant.DEFAULT_SUCCESS);

    let checkResult = Common.checkUrl(postData, [], request);
    if (checkResult == false) return;

    let artClass1 = await artClassModel.artTypeClass.findOne({
        where: {
            objectId: postData.objectId1
        },
    })

    let artClass2 = await artClassModel.artTypeClass.findOne({
        where: {
            objectId: postData.objectId2
        },
    })

    await artClassModel.artTypeClass.update({
        createdAt: artClass2.createdAt
    }, {
        where: {
            objectId: postData.objectId1
        },
    })

    await artClassModel.artTypeClass.update({
        createdAt: artClass1.createdAt
    }, {
        where: {
            objectId: postData.objectId2
        },
    })

    returnData.data = "成功"
    request.json(returnData)
}

async function list(req, request) {
    let postData = req.body
    let returnData = Common.clone(Constant.DEFAULT_SUCCESS);

    let checkResult = Common.checkUrl(postData, [], request);
    if (checkResult == false) return;

    let params = {}
    let artTypeClass = await artClassModel.artTypeClass.findAll({
        where: params,
        order: [['createdAt', 'ASC']],
    })
    artTypeClass = Common.clone(artTypeClass)

    returnData.data = artTypeClass
    request.json(returnData)
}

async function save(req, request) {
    let postData = req.body
    let returnData = Common.clone(Constant.DEFAULT_SUCCESS);

    let checkResult = Common.checkUrl(postData, ['name'], request);
    if (checkResult == false) return;

    let params = {
        name: postData.name,
        beizhu: postData.beizhu,
        orderNum: postData.orderNum,
        isSee: postData.isSee,
    }
    if (postData.objectId) {
        let result = await artClassModel.artTypeClass.update(params, {
            where: {
                objectId: postData.objectId
            }
        })
        returnData.data = result
    } else {
        params.objectId = sid.uuid()
        let result = await artClassModel.artTypeClass.create(params)
        returnData.data = result
    }

    request.json(returnData)
}

async function destroy(req, request) {
    let postData = req.body
    let returnData = Common.clone(Constant.DEFAULT_SUCCESS);

    let checkResult = Common.checkUrl(postData, ['objectId'], request);
    if (checkResult == false) return;

    let result = await artClassModel.artTypeClass.destroy({
        where: {
            objectId: postData.objectId
        }
    })
    returnData.data = result
    request.json(returnData)
}
